package cz.byteworks.android.myway.activities;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import cz.byteworks.android.myway.adapter.DataArrayAdapter;
import cz.byteworks.android.myway.db.DataHelper;
import cz.byteworks.android.myway.pojo.Way;

public class DataActivity extends Activity {

	List<Way> wayList;
	ArrayAdapter<Way> dataAdapter;
	ListView lv;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// nastavime celkove rozlozeni obrazovky
		setContentView(R.layout.data);
		// ziskame pohled graficke komponenty seznamu
		lv = (ListView) findViewById(R.id.dataListView);
		// z databaze nacitame seznam tras
		DataHelper dh = new DataHelper(this);
		wayList = dh.getAllWays(true);
		// inicializujeme adapter a predavame seznam polozek
		dataAdapter = new DataArrayAdapter<Way>(this, R.layout.data_item, wayList, getLayoutInflater());
		lv.setAdapter(dataAdapter); // nastavujeme adpater seznamu
		// pridame obsluhu kliknuti
		lv.setOnItemClickListener(new OnItemClickListener() {
			// metoda se provede pri kliknuti na polozku seznamu
			public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
				// zobrazime kontextove menu k dane polozce
				view.showContextMenu();
			}
		});
		// zaregistrujeme komponentu k pouzivani kont. menu
		registerForContextMenu(lv);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater mi = getMenuInflater();
		mi.inflate(R.menu.data_menu, menu);
		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.way_context_menu, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_add_new_path:
			menuPopupNewPath();
			break;
		case R.id.menu_prefs:
			Intent intent = new Intent(this, Preferences.class);
			startActivity(intent);
			break;
		case R.id.menu_about:
			createAboutDialog();
			break;
		}
		return true;
	}

	private void createAboutDialog() {
		TextView message = new TextView(this);
		String s = this.getText(R.string.about_text).toString();
		String link = "Twitter: twitter.com/koulik";
		message.setText(s+""+link);
		Linkify.addLinks(message, Linkify.ALL);
		
		message.setPadding(10, 10, 10, 10);
		message.setMovementMethod(LinkMovementMethod.getInstance());

		new AlertDialog.Builder(this).setTitle("About").setCancelable(true).setIcon(R.drawable.ic_launcher).setPositiveButton("Close", null).setView(message).create().show();
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		Way way = wayList.get(info.position);
		if (item.getTitle().toString().equals(getResources().getString(R.string.context_menu_open_map))) {
			Intent intent = new Intent(this, MyWayMapActivity.class);
			intent.putExtra("wayObj", way);
			startActivity(intent);
		}
		if (item.getTitle().toString().equals(getResources().getString(R.string.context_menu_open_way))) {
			Intent intent = new Intent(this, MyWayDetailActivity.class);
			intent.putExtra("wayObj", way);
			startActivity(intent);
		}
		if (item.getTitle().toString().equals(getResources().getString(R.string.context_menu_rename_way))) {
			menuPopupRenamePath(way.getName(), way.getId());
		}
		if (item.getTitle().toString().equals(getResources().getString(R.string.context_menu_delete_way))) {
			menuPopupDeletePath(way.getName(), way.getId());
		}

		return true;
	}

	private void menuPopupDeletePath(String wayName, final int wayId) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Delete Way");
		alert.setMessage("Do you really want to delete Way '" + wayName + "'?");

		final DataActivity ctx = this;
		alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				DataHelper dh = new DataHelper(ctx);
				dh.deleteWay(wayId);
				Toast.makeText(ctx, "Way deleted", 4000).show();
				dataAdapter.notifyDataSetChanged();
				onCreate(null);
			}
		});
		alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.show();
	}

	private void menuPopupNewPath() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Create Way");
		alert.setMessage("Enter Way Name:");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		alert.setView(input);
		final DataActivity ctx = this;
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				if (input.getText() != null && input.getText().toString().trim().length() > 0 && input.getText().toString().length() < 40) {
					DataHelper dh = new DataHelper(ctx);
					dh.insertNewWay(input.getText().toString());
					Toast.makeText(ctx, "New Way created", 4000).show();
					dataAdapter.notifyDataSetChanged();
					onCreate(null);
				} else {
					AlertDialog.Builder errDialog = new AlertDialog.Builder(ctx);
					errDialog.setMessage("Enter valid Way name (max. 40 chars)");
					errDialog.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							menuPopupNewPath();
						}
					});
					errDialog.show();
				}
			}
		});
		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.show();
	}

	private void menuPopupRenamePath(String originName, final int wayId) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Rename Way");
		alert.setMessage("Enter New Name:");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		input.setText(originName);
		input.selectAll();
		alert.setView(input);
		final DataActivity ctx = this;
		alert.setPositiveButton("Save", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				if (input.getText() != null && input.getText().toString().trim().length() > 0 && input.getText().toString().length() < 40) {
					DataHelper dh = new DataHelper(ctx);
					dh.updateWayName(input.getText().toString(), wayId);
					Toast.makeText(ctx, "Way has been renamed", 4000).show();
					dataAdapter.notifyDataSetChanged();
					onCreate(null);
				} else {
					AlertDialog.Builder errDialog = new AlertDialog.Builder(ctx);
					errDialog.setMessage("Enter valid Way name (max. 40 chars)");
					errDialog.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							menuPopupNewPath();
						}
					});
					errDialog.show();
				}
			}
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.show();
	}

}
